<?php

namespace app\hooks;

use app\api\model\Configs;
use app\api\model\ModeOrders;
use app\api\model\ModeOrdersLog;
use app\api\model\User;
use app\api\model\UserInvestBalanceLog;
use think\facade\Db;
use think\facade\Log;
use think\helper\Str;

class ModeTwoHook
{


    public static $RATE_OF_STATIC = 10;
    public const RATE_OF_STATIC = 10;
    public const RATE_OF_INVEST = 1;
    public const RATE_OF_PARTNER_DIRECT = 20;
    public const RATE_OF_HY_DIRECT = [10, 10];
    public const RATE_OF_PARTNER_PINGJI = 10;

    private static function rateInit()
    {
        self::$RATE_OF_STATIC = 5;
    }

    public static function paid_run($order_id)
    {

        if ($order_info = ModeOrders::where('id', $order_id)->whereIn('type', 3)->findOrEmpty()->toArray()) {

            $user_info = User::findOrEmpty((int)$order_info['user_id'])->toArray();

            $achievements = ['partner_hy_direct' => [], 'partner_direct' => [], 'partner_pingji' => []];

            if ($parent_users = ModeHook::getUserParents((int)$user_info['pid'])) {

                $direct_parent_user = $parent_users[0];

                if ($direct_parent_user['invest_count'] > 0) {

                    $achievements['partner_direct'][$direct_parent_user['id']] = $partner_pingji_amount = ModeHook::computePercentAmount($order_info['principal'], self::RATE_OF_PARTNER_DIRECT);

                } else {

                    //会员推合伙人，会员直接得奖励
                    $achievements['partner_hy_direct'][$direct_parent_user['id']] = ModeHook::computePercentAmount($order_info['principal'], self::RATE_OF_HY_DIRECT[0]);

                    $partner_pingji_amount = 0;

                    //循环所有父级用户
                    foreach ($parent_users as $pk => $parent_user) {

                        if ($pk > 0) {

                            if ($parent_user['invest_count'] > 0) {

                                $achievements['partner_direct'][$parent_user['id']] = $partner_pingji_amount = ModeHook::computePercentAmount($order_info['principal'], self::RATE_OF_HY_DIRECT[1]);

                                break;
                            }

                        }

                    }

                }

                //循环所有父级用户
                foreach ($parent_users as $pk => $parent_user) {

                    if ($pk > 0) {

                        if ($parent_user['invest_count'] > 0 && !isset($achievements['partner_direct'][$parent_user['id']])) {

                            $partner_pingji_amount = ModeHook::computePercentAmount($partner_pingji_amount, self::RATE_OF_PARTNER_PINGJI);

                            if ($partner_pingji_amount >= 1000) {

                                $achievements['partner_pingji'][$parent_user['id']] =  $partner_pingji_amount;

                            } else {

                                break;

                            }

                        }

                    }

                }

            }

            ModeOrders::where('id', $order_info['id'])->update(['active_achievements' => json_encode($achievements), 'last_achievements_time' => time()]);

            self::release($order_info['id'], $achievements);
        }
        return true;
    }


    public static function static_run($begin_time, $end_time)
    {
        //整理时间周期
        $dateBetween = [date('Y-m-d 00:00:00', strtotime($begin_time)), date('Y-m-d 23:59:59', strtotime($end_time))];

        //查询当天静态释放总额
        $total_invest_static_amount = (int)abs(UserInvestBalanceLog::whereBetween('create_time', $dateBetween)->where('type', 'mode_static_release')->sum('amount'));
        $total_invest_paid_amount = (int)ModeOrders::whereBetween('pay_time', $dateBetween)->where('is_delete', 0)->where('type', 4)->where('status', 'payed')->sum('principal');

        if ($total_invest_static_amount_limit = (int)Configs::where('alias', 'MODE_TWO_PARTNER_STATIC_LIMIT')->value('content')) {

            $total_invest_static_amount = min($total_invest_static_amount, $total_invest_static_amount_limit);

        }

        if ($total_invest_paid_amount_limit = (int)Configs::where('alias', 'MODE_TWO_PARTNER_STATIC_LIMIT')->value('content')) {

            $total_invest_paid_amount = min($total_invest_paid_amount, $total_invest_paid_amount_limit);

        }

        $achievements = ['partner_static' => [], 'partner_invest' => []];

        //查询全网合伙人
        if ($partners = User::where('invest_count', '>', 0)->field('id, invest_count')->select()) {

            $partners = $partners->toArray();

            $total_invest_count = (int)array_sum(array_column($partners, 'invest_count'));


            if ($total_invest_static_amount > 0) {

                $total_invest_static_amount = ModeHook::computePercentAmount($total_invest_static_amount, self::RATE_OF_STATIC);

            }

            if ($total_invest_paid_amount > 0) {

                $total_invest_paid_amount = ModeHook::computePercentAmount($total_invest_paid_amount, self::RATE_OF_INVEST);

            }

            foreach ($partners as $pk => $partner) {


                $achievements['partner_static'][$partner['id']] = ModeHook::computePercentAmount($total_invest_static_amount, $partner['invest_count'], $total_invest_count);


                $achievements['partner_invest'][$partner['id']] = ModeHook::computePercentAmount($total_invest_paid_amount, $partner['invest_count'], $total_invest_count);


                unset($partners[$pk]);
            }

        }

        return self::release(0, $achievements);

    }

    private static function release($order_id, $achievements)
    {

        foreach ($achievements as $speedup_type => $amounts) {
            if ($amounts) {
                foreach ($amounts as $user_id => $amount) {
                    self::releaseAction($user_id, $amount, $order_id, 'speedup', $speedup_type);
                }
            }
        }
        return true;
    }

    private static function releaseAction($user_id, $amount, $from_order_id, $type, $speedup_type)
    {
        if ($amount <= 0) {
            return true;
        }

        Db::startTrans();

        try {

            $log_content = '['.$from_order_id.']'.implode('-', [
                    data_get(ModeOrdersLog::TYPES, $type, ''),
                    data_get(ModeOrdersLog::SPEEDUP_TYPES, $speedup_type, '')
                ]);

            if ($speedup_type == 'partner_hy_direct') {

                $balance = $amount;
                $amount = 0;

            } else {

                //获取最多可销毁福利分
                $amount = $balance = min($amount, (int)User::where('id', $user_id)->value('welfare_points'));

            }

            ModeHook::createIncome($user_id, $balance, 0, $amount, 'welfare_points', $type, $log_content);

            Db::commit();
        } catch (\Exception $exception) {

            Db::rollback();

            Log::error('ModeTwoOrderRelease:'.json_encode(['message' => $exception->getMessage(), 'file' => $exception->getFile(), 'line' => $exception->getLine()], JSON_UNESCAPED_UNICODE));
        }

        return true;
    }





}